package com.tzbank.services.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;

import com.dc.eai.data.CompositeData;
import com.tzbank.consumer.BackstageServiceScheduler;
import com.tzbank.consumer.FaceServiceScheduler;
import com.tzbank.consumer.FingerprintServiceScheduler;
import com.tzbank.consumer.VoiceServiceScheduler;
import com.tzbank.consumer.WisdomServiceScheduler;
import com.tzbank.esbService.util.CodeUtil;
import com.tzbank.esbService.util.EsbConversionUtil;
import com.tzbank.esbService.util.GeneralSeqNo;
import com.tzbank.services.CommonEsbService;
import com.tzbank.utils.SpringContextUtils;

import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

@Slf4j
@Service(value = "commonEsbService")
@RefreshScope
public class CommonEsbServiceImpl implements CommonEsbService {
	
	 @Autowired
    private FingerprintServiceScheduler fingerprintServiceScheduler;
	 @Autowired
	private FaceServiceScheduler faceServiceScheduler;
	 @Autowired
	private VoiceServiceScheduler voiceServiceScheduler;
	 @Autowired
	private WisdomServiceScheduler wisdomServiceScheduler;
	 @Autowired
	private BackstageServiceScheduler backstageServiceScheduler;
	 @Autowired
	private Environment environment;

	@Override
	public CompositeData commonEsbService(Map<String, Object> inputMap) {
		CompositeData result = new CompositeData();
		System.out.println("====================ESB========================");
		String SeqNo = GeneralSeqNo.generalGlobalSeqNo("ESB");// 服务流水
		// 调用的服务名称
		String serviceName = "";
		String methodName = "";
		String servicesParam = "";
		
		String serviceCode = (String) ((Map<String, Object>) inputMap.get("head")).get("serviceCode");
		String serviceScene = (String) ((Map<String, Object>) inputMap.get("head")).get("serviceScene");
		String CONSUMER_SEQ_NO = (String) ((Map<String, Object>) inputMap.get("head")).get("consumerSeqNo");

		Map<String, Object> publicMap = new HashMap<String, Object>();
		publicMap.put("CONSUMER_SEQ_NO", CONSUMER_SEQ_NO);// 是服务请求系统的流水号
		publicMap.put("ESB_SEQ_NO", "");// （ESB产生的流水号）为ESB系统的流水号

		publicMap.put("BUSS_SEQ_NO", "");//// 业务流水号）为应用头请求中BUSS_SEQ_NO
		publicMap.put("SERV_SEQ_NO", SeqNo);// 服务生成流水
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (null == environment) {
			resultMap.put("code", "900001");
			resultMap.put("msg", "读取配置文件esbConfigPath的结果为空，请检查日志！");
			return toChang(resultMap, publicMap);
		} else {
			servicesParam = String.valueOf(environment.getProperty(serviceCode + "_" + serviceScene)).trim();
			String Name = String.valueOf(environment.getProperty("service"+serviceCode + "_" + serviceScene)).trim();
			//String Name ="tzbank-face&intoface";
			try {
				serviceName = Name.split("&")[0];
				methodName=Name.split("&")[1];
			} catch (Exception e) {
				resultMap.put("code", "900003");
				resultMap.put("msg", "通过ESB的服务代码:" + serviceCode + "_" + serviceScene + "找不到对应的服务相关参数，请检查配置文件！serviceName");
				return toChang(resultMap, publicMap);
			}

		}
		if (StringUtil.isEmpty(serviceName) ||StringUtil.isEmpty(serviceName)) {
			resultMap.put("code", "900002");
			resultMap.put("msg", "通过ESB的服务代码:" + serviceCode + "_" + serviceScene + "找不到对应的服务相关参数，请检查配置文件！");
			return toChang(resultMap, publicMap);
		}
		log.info("开始调用服务:" + SeqNo + ",通过ESB的服务代码:" + serviceCode + "_" + serviceScene + "调用Bosent服务：" + serviceName);
		Map<String, Object> model = getInPutParam(inputMap, servicesParam);// 将参数转换成系统需要的字段	
		model.put("consumerSeqNo", CONSUMER_SEQ_NO);
		Method []ObjWorkEffMethod = null;
			if("tzbank-face".equals(serviceName)) {
				ObjWorkEffMethod = faceServiceScheduler.getClass().getDeclaredMethods();
			}else if("tzbank-fingerprint".equals(serviceName)) {
				ObjWorkEffMethod = fingerprintServiceScheduler.getClass().getDeclaredMethods();
			}else if("tzbank-voice".equals(serviceName)) {
				ObjWorkEffMethod = voiceServiceScheduler.getClass().getDeclaredMethods();
			}else if("tzbank-wisdom".equals(serviceName)) {
				ObjWorkEffMethod = wisdomServiceScheduler.getClass().getDeclaredMethods();
			}else if("tzbank-backstage".equals(serviceName)) {
				ObjWorkEffMethod = backstageServiceScheduler.getClass().getDeclaredMethods();
			}else {
				resultMap.put("code", "900002");
				resultMap.put("msg", "通过ESB的服务代码:" + serviceCode + "_" + serviceScene + "找不到对应的服务相关参数，请检查配置文件！");
				return toChang(resultMap, publicMap);
			}
		
		for(Method workEffMethod:ObjWorkEffMethod) {
			if(workEffMethod.getName().equals(methodName)) {
				try {
					if("tzbank-face".equals(serviceName)) {
						resultMap = (Map<String, Object>) workEffMethod.invoke(faceServiceScheduler, model);
					}else if("tzbank-fingerprint".equals(serviceName)) {
						resultMap = (Map<String, Object>) workEffMethod.invoke(fingerprintServiceScheduler, model);
					}else if("tzbank-voice".equals(serviceName)) {
						resultMap = (Map<String, Object>) workEffMethod.invoke(voiceServiceScheduler, model);
					}else if("tzbank-wisdom".equals(serviceName)) {
						resultMap = (Map<String, Object>) workEffMethod.invoke(wisdomServiceScheduler, model);
					}else if("tzbank-backstage".equals(serviceName)) {
						resultMap = (Map<String, Object>) workEffMethod.invoke(backstageServiceScheduler, model);
					}
				} catch (IllegalAccessException e) {
					log.info("错误服务:" + SeqNo + ",通过ESB的服务代码:" + serviceCode + "_" + serviceScene + "调用Bosent服务：" + serviceName);
				} catch (IllegalArgumentException e) {
					log.info("错误服务:" + SeqNo + ",通过ESB的服务代码:" + serviceCode + "_" + serviceScene + "调用Bosent服务：" + serviceName);
				} catch (InvocationTargetException e) {
					log.info("错误服务:" + SeqNo + ",通过ESB的服务代码:" + serviceCode + "_" + serviceScene + "调用Bosent服务：" + serviceName);
				}
				break;
			}
		}
		
		result = toChang(resultMap, publicMap);
		log.info("调用ESB服务结束:" + SeqNo + ",返回结果："+result.toString());
		return result;
	}
	
	
	/**
	 * 处理请求参数 字段对应 demandId-bizId,verifyFlag-zimId
	 */
	public Map<String, Object> getInPutParam(Map<String, Object> inputMap, String servicesParam) {

		String[] ss = servicesParam.split(",");
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> mapParm = new HashMap<String, Object>();
		for (int i = 0; i < ss.length; i++) {
			if (2 == ss[i].split("-").length) {
				map.put(ss[i].split("-")[0], ss[i].split("-")[1]);
			}
		}
		for (Entry<String, Object> vo : map.entrySet()) {
			String key=(String) inputMap.get(vo.getKey());//该值是JSON字符串
			String value =(String) vo.getValue();
			if("metainfo".equals(value)) {
				
				mapParm.put((String) vo.getValue(), JSONObject.fromObject(key));
			}else {
				mapParm.put((String) vo.getValue(), key);
			}
		}
		return mapParm;
	}
	
	/**
	 * 将返回结果封装
	 * 
	 * @param resultMap
	 * @param publicMap
	 * @return
	 */
	public  CompositeData toChang(Map<String, Object> resultMap, Map<String, Object> publicMap) {

		CompositeData result = new CompositeData();
		// 组装入参Map
		Map<String, Object> inputMap = new HashMap<String, Object>();
		Map<String, Object> reqSysHead = new HashMap<String, Object>();
		Map<String, Object> reqAppHead = new HashMap<String, Object>();
		List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
		Map<String, Object> retCode = new HashMap<String, Object>();
		reqSysHead.put("consumerSeqNo", publicMap.get("CONSUMER_SEQ_NO")); // 是服务请求系统的流水号
		reqSysHead.put("esbSeqNo", publicMap.get("ESB_SEQ_NO")); // （ESB产生的流水号）为ESB系统的流水号
		// 应用头应答数据
		reqAppHead.put("bussSeqNo", publicMap.get("BUSS_SEQ_NO")); // 业务流水号）为应用头请求中BUSS_SEQ_NO
		reqAppHead.put("servSeqNo", publicMap.get("SERV_SEQ_NO"));// 服务流水
		inputMap.put("appHead", reqAppHead);
		if (resultMap.isEmpty()) {
			retCode.put("retMsg", "服务异常或者参数错误，请通知相关人员！！");
			retCode.put("retCode", "5555555555");
			ret.add(retCode);
			reqSysHead.put("ret", ret);
			reqSysHead.put("retStatus", "F");

		} else if (CodeUtil.CODE_200.getCode().equals(resultMap.get("code"))) {// 结果成功获取
			//
			retCode.put("retMsg", "成功");
			retCode.put("retCode", "000000");
			ret.add(retCode);
			reqSysHead.put("ret", ret);
			reqSysHead.put("retStatus", "S");

		} else {// 程序异常
				//
			retCode.put("retMsg", resultMap.get("msg"));
			retCode.put("retCode", resultMap.get("code"));
			ret.add(retCode);
			reqSysHead.put("ret", ret);
			reqSysHead.put("retStatus", "F");

		}

		inputMap.put("sysHead", reqSysHead);
		inputMap.put("handleResult", resultMap.get("data"));// y
		// Map转换Esb报文
		result = EsbConversionUtil.mapToCompositeData(inputMap);
		return result;
	}


}
